package lion.framework.core.web.anno;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.apache.commons.io.FilenameUtils;

import lion.dev.lang.MapJ;
import lion.framework.core.anno.AnnoProcessor;
import lion.framework.core.anno.AnnotationProcessorManager;
import lion.framework.core.anno.IAnnotationProcessor;
import lion.framework.core.web.path.PathNode;
import lion.framework.core.web.path.PathNodeMapping;
import lion.framework.core.web.path.PathVar;

@AnnoProcessor(MultiPath.class)
public class MultiPathAnnoProcessor implements IAnnotationProcessor {

	@Override
	public void processe(MapJ ctx, Annotation anno) throws Exception {

		Object o = ctx.get(AnnotationProcessorManager.ANNO_CONTEXT_TARGET);
		if (o == null) { return; }
		Method method = (Method) o;
		MultiPath multiPath = (MultiPath) anno;

		Path[] paths = multiPath.value();

		Class<?> clazz = (Class<?>) ctx.get(AnnotationProcessorManager.ANNO_CONTEXT_CLASS);

		Namespace ns = clazz.getAnnotation(Namespace.class);
		String pkg = "";
		if (ns != null) {
			pkg = ns.value();
		}
		if (!pkg.endsWith("/")) {
			pkg += "/";
		}

		for (Path path : paths) {
			for (String p : path.value()) {

				String pathm = FilenameUtils.separatorsToUnix(pkg + p);
				pathm = PathVar.replacePathVars(pathm);

				PathNode node = PathNodeMapping.add(pathm);
				node.setMethodType(path.method().name());
				node.setMethod(method);
				ViewProcessor processor = new ViewProcessor();
				ctx.put(PathMappingProcessor.PATH_NODE, node);
				processor.processe(ctx, method.getAnnotation(Result.class));
				ctx.remove(PathMappingProcessor.PATH_NODE);
			}
		}
	}
}
